# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Ray Donnelly <mingw.android@gmail.com>

_realname=docutils
pkgbase=mingw-w64-python-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-python-${_realname}")
provides=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
conflicts=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
replaces=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
pkgver=0.17.1
pkgrel=1
pkgdesc="Set of tools for processing plaintext docs into formats such as HTML, XML, or LaTeX (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
license=('custom')
url="https://docutils.sourceforge.io/"
depends=("${MINGW_PACKAGE_PREFIX}-python")
makedepends=("${MINGW_PACKAGE_PREFIX}-python-setuptools")
source=(http://downloads.sourceforge.net/${_realname}/${_realname}-${pkgver}.tar.gz)
sha256sums=('686577d2e4c32380bb50cbb22f575ed742d58168cee37e99117a854bcd88f125')
noextract=(${_realname}-${pkgver}.tar.gz)

prepare() {
  [[ -d ${srcdir}/${_realname}-${pkgver} ]] && rm -rf ${srcdir}/${_realname}-${pkgver}
  tar -xzf ${srcdir}/${_realname}-${pkgver}.tar.gz -C ${srcdir} || true

  rm -rf python-build-${CARCH} | true
  cp -r "${_realname}-${pkgver}" "python-build-${CARCH}"
}

build() {
  msg "Python build for ${CARCH}"
  cd "${srcdir}/python-build-${CARCH}"
  MSYS2_ARG_CONV_EXCL="--prefix=;--install-scripts=;--install-platlib=" \
      ${MINGW_PREFIX}/bin/python setup.py build --build-lib=build/python
  find build/python -type f -exec \
      sed -i "1s,^#! \?/usr/bin/\(env \|\)python$,#!${MINGW_PREFIX}/bin/python," {} \;
}

check() {
  export LANG=en_US.UTF-8
  msg "Python test for ${CARCH}"
  cd "${srcdir}/python-build-${CARCH}"
  MSYS2_ARG_CONV_EXCL="--prefix=;--install-scripts=;--install-platlib=" \
       PYTHONPATH="$PWD/build/python/" ${MINGW_PREFIX}/bin/python test/alltests.py
}

package() {
  cd "${srcdir}/python-build-${CARCH}"
  MSYS2_ARG_CONV_EXCL="--prefix=;--install-scripts=;--install-platlib=" \
  ${MINGW_PREFIX}/bin/python setup.py build --build-lib=build/python \
      install --prefix=${MINGW_PREFIX} --root="${pkgdir}" --optimize=1 --skip-build

  local _mingw_prefix=$(cygpath -am ${MINGW_PREFIX})

  for _f in "${pkgdir}${MINGW_PREFIX}"/bin/*.py; do
    sed -e "s|${_mingw_prefix}/bin/|/usr/bin/env |g" -i ${_f}
  done

  # symlink without .py
  for f in "${pkgdir}${MINGW_PREFIX}"/bin/*.py; do
    ln -s "$(basename $f)" "${pkgdir}${MINGW_PREFIX}/bin/$(basename $f .py)"
    # fix so the file is a script that can run with no issues on the command-line w/o
    # specifying an interpreter
    sed -e "s|/usr/bin/env python3.exe|${MINGW_PREFIX}/bin/python.exe|g" -i "${pkgdir}${MINGW_PREFIX}/bin/$(basename $f .py)"
  done

  # setup license
  install -D -m644 COPYING.txt "${pkgdir}${MINGW_PREFIX}/share/licenses/python-${_realname}/COPYING.txt"
  install -D -m644 licenses/python* "${pkgdir}${MINGW_PREFIX}/share/licenses/python-${_realname}/"
}
